import random
from django.core.cache import cache

def generate_email_code(email):
    """生成6位数字验证码"""
    code = str(random.randint(100000, 999999))
    cache.set(f"email_code_{email}", code, timeout=300)  # 5分钟有效期
    return code

def verify_email_code(email, code):
    """验证邮箱验证码"""
    if not email or not code:
        return False
    
    cached_code = cache.get(f"email_code_{email}")
    if cached_code is None:
        return False
    
    # 严格比较验证码
    is_valid = cached_code == code
    
    # 验证通过后删除验证码，确保一次性使用
    if is_valid:
        cache.delete(f"email_code_{email}")
        
    return is_valid